package cn.minhx.mw.dtp.sdk.registry.redis;

import cn.minhx.mw.dtp.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.minhx.mw.dtp.sdk.domain.model.valobj.RegistryEnumVO;
import cn.minhx.mw.dtp.sdk.registry.Registry;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.Collection;

import static com.alibaba.fastjson2.JSON.toJSONString;

/**
 * 注册中心【Redis实现】
 *
 * @author minhx
 */
@Slf4j
public class RedisRegistryImpl implements Registry {

    private final RedissonClient redissonClient;

    public RedisRegistryImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public void reportThreadPoolConfigList(Collection<ThreadPoolConfigEntity> configList) {
        RList<ThreadPoolConfigEntity> list = redissonClient.getList(RegistryEnumVO.DTP_THREAD_POOL_CONFIG_LIST.getKey());
        list.delete();
        list.addAll(configList);
        list.expire(Duration.ofDays(30));
        log.debug("[动态线程池-配置上报] threadPoolConfigList={}", toJSONString(configList));
    }

    @Override
    public void reportThreadPoolConfig(ThreadPoolConfigEntity config) {
        String cacheKey = RegistryEnumVO.DTP_THREAD_POOL_CONFIG.getKey() + "_" + config.getAppName() + "_" + config.getThreadPoolName();
        RBucket<ThreadPoolConfigEntity> bucket = redissonClient.getBucket(cacheKey);
        bucket.set(config, Duration.ofDays(30));
        log.debug("[动态线程池-配置上报] threadPoolConfig={}", toJSONString(config));
    }
}
